namespace array_demo.Model.Algorithm
{
    public class TestSearch
    {
        /// <summary>
        /// 二分查找法（对于有序数组）
        /// </summary>
        /// <param name="array"></param>
        /// <param name="target"></param>
        /// <returns></returns>
        public static int BinarySearch(int[] array, int target)
        {
            int l = 0;
            int r = array.Length - 1;
            while (l <= r)
            {
                // int mid=(l+r)/2; 数据过大时会溢出
                int mid = l + (r - l) / 2;
                if (array[mid] > target)
                    l = mid + 1;
                else if (array[mid] < target)
                    r = mid - 1;
                else
                    return mid;
            }
            return -1;
        }

        
    }
}